﻿using System;

public static partial class Extensions
{
    public static DateTime ToExcelDateTime(this double @this)
    {
        var zeroTime = new DateTime(1900, 1, 1);
        var second = @this * 24 * 60 * 60;
        return zeroTime.AddSeconds(second).AddDays(-1);
    }

    /// <summary>
    ///     计算目标日期UTC到1970年的时间差（unix基础时间）
    /// </summary>
    /// <param name="this"></param>
    /// <returns></returns>
    public static double GetUtcSecondsFromBaseTime(this DateTime @this)
    {
        return Math.Round((@this.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds);
    }


    /// <summary>
    ///     转换微信DateTime时间到C#时间
    /// </summary>
    /// <param name="dateTimeFromXml">微信DateTime</param>
    /// <returns></returns>
    public static DateTime GetDateTimeFromXml(this  long dateTimeFromXml)
    {
        return new DateTime(1970, 1, 1).AddTicks((dateTimeFromXml + 8 * 60 * 60) * 10000000);
    }


    /// <summary>
    ///     获取UNIX时间戳
    /// </summary>
    /// <param name="dateTime">时间</param>
    /// <returns></returns>
    public static long GetUnixTimestamp(this DateTime @this)
    {
        return (@this.Ticks - new DateTime(1970, 1, 1).Ticks) / 10000000 - 8 * 60 * 60;
    }

    /// <summary>
    ///     A DateTime extension method that converts the @this to an epoch time span.
    /// </summary>
    /// <param name="this">The @this to act on.</param>
    /// <returns>@this as a TimeSpan.</returns>
    public static TimeSpan ToEpochTimeSpan(this DateTime @this)
    {
        return @this.Subtract(new DateTime(1970, 1, 1));
    }
}